import wepy from 'wepy'
import Tips from './tips'

export default class wxUtils {
  // 等待程序加载
  static async waitAppInit() {
    if (!wepy.$instance.globalData.isInit) {
      Tips.loading("程序加载中")
      while (true) {
        await this.sleep(200)
        if (wepy.$instance.globalData.isInit) {
          Tips.loaded()
          break
        }
        if (wepy.$instance.globalData.initFail) {          
          Tips.loaded()
          return false // 初始化失败后，直接停止运行
        }
      }
    }
    return true;
  }

  // 跳转路由 （注意URl是绝对路径 /page/home/index
  static redirectToPage(url, tweeterGoWay = false) {
    const pages = getCurrentPages();

    if (url.indexOf('/') != 0) {
      url = "/" + url; //绝对路径
    }
    const index = pages.findIndex(item => ('/' + item.__route__) == url);

    if (index >= 0) {
      const delta = pages.length - 1 - index;
      //  当前页，不跳
      if (delta == 0) {
        return
      } else if (delta == 1) { // 上一页，返回
        wepy.navigateBack({
          delta: delta
        });
        return
      }
    }

    // 跳转tabbar
    if(this.isTabPage(url)) {
      wepy.switchTab({url:url,fail:function(){
          this.openWxaPage(url,pages.length) // 尝试另外一种方式打开
      }})
      return
    }

    // 清除所有页面，从新页面打开
    if (tweeterGoWay) {
      wx.reLaunch({
        url: url
      })
      return
    }

    //  尝试另外一种方式打开
    this.openWxaPage(url, pages.length);
  }

  // 尝试navigateTo打开一个页面
  static openWxaPage(url, curPagesLength) {
    console.log(url)
    let that = this;
    if (curPagesLength < 8) {
      wepy.navigateTo({
        url: url
      }).catch(ex => {
        if (ex.errMsg && ex.errMsg.indexOf("is not found") > 0) {
          that.goToErrorPage(404.1);
        } else {
          throw ex;
        }
      });
    } else {
      // 超过了,开启新的页队栈
      wepy.reLaunch({
        url: url
      }).catch(ex => {
        if (ex.errMsg && ex.errMsg.indexOf("is not found") > 0) {
          that.goToErrorPage(404.1);
        } else {
          throw ex;
        }
      });
    }
  }

  // 判断是否为tabbar
  static isTabPage(url){
    let list = wepy.$instance.config.tabBar.list
    let flag = false
    list.forEach(item => {
      if (`/${item.pagePath}` == url) {
        flag = true
      }
    })
    if (flag) {
      return url
    } else {
      return false
    }
  }

  // 基础库检查
  static isSDKExipred() {
    const {
      SDKVersion
    } = wx.getSystemInfoSync();
    return SDKVersion == null || SDKVersion < '2.0.0'
  }

  //  获取当前页面的URl，带参数
  static getCurrentPageUrlWithArgs() {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    let url = "/" + currentPage.route;
    const options = currentPage.options;
    let urlWithArgs = "";
    for (let key in options) {
      const value = options[key];
      urlWithArgs += `${key}=${value}&`;
    }
    if (urlWithArgs != "") {
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
      url = `${url}?${urlWithArgs}`;
    }
    return url
  }


  // 跳转报错页
  static goToErrorPage(bizcode, msg = null) {
    const returnUrl = escape(this.getCurrentPageUrlWithArgs()) // 获取返回的PageUrl及参数
    ///跳转到系统异常页面
    if (msg) {
      wepy.redirectTo({
        url: '/pages/error/index?type=' + bizcode + '&msg=' + msg + '&returnUrl=' + returnUrl
      });
    } else {
      wepy.redirectTo({
        url: '/pages/error/index?type=' + bizcode + '&returnUrl=' + returnUrl
      });
    }
  }

  // 等待睡眠
  static sleep(s) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(s)
      }, s)
    })
  }

  // 等待异步结果
  static async awtAsyncFun(asyncFun)
  {
      return await asyncFun.catch(ex =>
      {
        throw(ex);
      })
  }
}
